package servlet;

import database.DataBaseConnection;
import net.sf.json.JSONObject;
import utility.Utility;
import data.GetSeries;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;

@WebServlet(name = "SeriesServlet")
public class SeriesServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Type", "text/html");
        response.setCharacterEncoding("UTF-8");
        String start = request.getParameter("start");
        String end = request.getParameter("end");
        String operator = request.getParameter("operator");
        String[] table = request.getParameterValues("table");
        String span = request.getParameter("span");
        JSONObject jsonObject = new JSONObject();
        Connection connection = DataBaseConnection.getConnection();
        if (connection != null) {
            for (String name : table) {
                String tableName = Utility.getTableName(Integer.parseInt(name));
                GetSeries getSeries = new GetSeries(start, end, operator, tableName, span);
                jsonObject.put(tableName, getSeries.getSeriesData(connection));
            }
            DataBaseConnection.closeConnection(connection);
        }
        String responseText = jsonObject.toString();
        PrintWriter printWriter = response.getWriter();
        printWriter.print(responseText);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doPost(request, response);
    }
}
